/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.webos.java.passwords;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.json.JSONObject;
import org.webos.java.base.Dialog;
import org.webos.java.base.DialogType;
import org.webos.java.base.NetworkManager;
import org.webos.java.base.RemoteMessage;
import org.webos.java.base.utils.CryptoUtil;
import org.webos.java.root.Log;

/**
 *
 * @author Kostya
 */

@DialogType(jsClass="passwords.Settings")
public class SettingsWindow extends Dialog<PasswordManager>{

    public SettingsWindow(PasswordManager aManager) {
        super(aManager);
        show();
    }

    @RemoteMessage
    public JSONObject okClick(JSONObject aObject){
        try {
            String oldPassword = aObject.optString("old_pass", "");
            String newPassword = aObject.optString("new_pass", "");
            String newPassword2 = aObject.optString("new_pass2", "");
            String masterPassword = getApplication().getSecret("master_password", "");
            if(!masterPassword.equals(oldPassword))
                return NetworkManager.getErrorObject(1016, "Old password you provided is incorrect");
            if("".equals(newPassword))
                return NetworkManager.getErrorObject(1017, "New password can't be empty");
            if(!newPassword.equals(newPassword2))
                return NetworkManager.getErrorObject(1018, "Passwords don't match");
            PreparedStatement st = getApplication().connection.prepareQuery("select id, username, password from PASSWORDS");
            PreparedStatement upd = getApplication().connection.prepareQuery(
                    "update PASSWORDS set username=?, password=? where id=?");
            ResultSet rset = st.executeQuery();
            while(rset.next()){
                int id = rset.getInt(1);
                String login = CryptoUtil.decode(masterPassword, rset.getString(2));
                String password = CryptoUtil.decode(masterPassword, rset.getString(3));
                upd.setString(1, CryptoUtil.encode(newPassword, login));
                upd.setString(2, CryptoUtil.encode(newPassword, password));
                upd.setInt(3, id);
                upd.execute();
            }
            getApplication().setSecret("master_password", newPassword);
            getApplication().lockPassword();
            getApplication().connection.commit();
            closeDialog(aObject);
            getApplication().grid.displayPasswords(getApplication().grid.categorieItem);
            return null;
        } catch (Throwable t) {
            getApplication().connection.rollback();
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
        return NetworkManager.getErrorObject(1019, "Can't update master password");
    }

}
